package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.entity.Role;
import cn.ztydata.teachingsystem.heaven.entity.Teacher;
import cn.ztydata.teachingsystem.heaven.service.AuthorizeService;
import cn.ztydata.teachingsystem.heaven.web.dto.AuthCourseDto;
import cn.ztydata.teachingsystem.heaven.web.dto.RoleDto;
import cn.ztydata.teachingsystem.heaven.web.dto.TeacherDto;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * 用户授权控制器类
 *
 * @author fanruiping
 * @since 2014-12-01
 */
@Controller
@RequestMapping("/authorize")
public class AuthorizeController extends BaseController {
    @Autowired
    private AuthorizeService authorizeService;

    /**
     * 获取授权用户列表
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-02
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult list(@RequestParam(value = "type",required = false, defaultValue = "0") int type, @RequestParam(value = "id",required = false, defaultValue = "0") long id){
        long deptId = 0;
        long specialtyId = 0;

        Integer[] roleIds = {Roles.SUPER_ADMIN,Roles.COLLEGE_USER,Roles.DEPT_ADMIN,Roles.SPEC_LEADER};

        //判断type值是否正确
        if(!Arrays.asList(roleIds).contains(type)){
            log.debug("type is wrong:0 > Arrays.binarySearch(roleIds, type)");

            return new JsonResultList<>(false,"请求的数据不存在");
        }

        //判断是否是授权系部管理员
        if(Roles.DEPT_ADMIN == type){
            log.debug("type is deptAdmin:Roles.DEPT_ADMIN == type");

            deptId = id;
        }

        //判断是否是专业负责人
        if(Roles.SPEC_LEADER == type){
            log.debug("type is specLeader:Roles.SPEC_LEADER == type");

            specialtyId = id;
        }

        List<Teacher> entities = authorizeService.getAuthorisedList(type, deptId, specialtyId);

        log.debug("return AuthorizeUserList");

        return new JsonResultList<>(mapper.mapList(entities, TeacherDto.class));
    }

    /**
     * 新增授权
     * @param dto
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-02
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(@RequestBody RoleDto dto){
        Integer[] roleIds = {Roles.SUPER_ADMIN,Roles.COLLEGE_USER,Roles.DEPT_ADMIN,Roles.SPEC_LEADER};

        long id = 0;

        //判断type值是否正确
        if(!Arrays.asList(roleIds).contains(dto.getType())){
            log.debug("user role is wrong:Arrays.asList(roleIds).contains(dto.getType())");

            return new JsonResultList<>(false,"授权数据有误");
        }

        Role entity = mapper.map(dto, Role.class);

        entity.setDeptId(id);
        entity.setSpecialtyId(id);

        //判断是否是专业负责人
        if(Roles.SPEC_LEADER == dto.getType()){
            log.debug("user role is specialty leader");

            entity.setSpecialtyId(dto.getDeptId());
        }else if(Roles.DEPT_ADMIN == dto.getType()){
            log.debug("user role is department admin");

            entity.setDeptId(dto.getDeptId());
        }

        //判断授权是否已存在
        if(authorizeService.checkIsExist(entity)){
            log.debug("authorize is exist");

            return new JsonResult(false, "请勿重复授权");
        }

        try {
            authorizeService.add(entity);

            log.debug("add authorize success:return true");

            return new JsonResult(true, "授权成功");
        }catch(ServiceException ex){
            log.debug("add authorize fail:return false");

            return new JsonResult(false,ex.getMessage());
        }
    }

    /**
     * 取消授权
     * @param teacherId
     * @param type
     * @param departId
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-02
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult cancel(@RequestParam(value = "teacherId",required = false, defaultValue = "1") long teacherId,
                             @RequestParam(value = "type",required = false, defaultValue = "1") int type,
                             @RequestParam(value = "departId",required = false, defaultValue = "1") long departId){
        long departmentId = 0;
        long specialtyId = 0;

        //判断是否是专业负责人
        if(Roles.SPEC_LEADER == type){
            log.debug("user role is specialty admin");

            specialtyId = departId;
        }else if(Roles.DEPT_ADMIN == type){//判断是否是系部管理员
            log.debug("user role is department admin");

            departmentId = departId;
        }

        try {
            authorizeService.delete(teacherId, type, departmentId, specialtyId);

            log.debug("delete authorize success:return true");

            return new JsonResult(true, "取消授权成功");
        }catch (ServiceException ex){
            log.debug("delete authorize fail:return false");

            return new JsonResult(false, "取消授权失败");
        }
    }

    /**
     * 授权课程负责人
     *
     * @author chenxin
     * @since 2014/12/24
     */
    @RequestMapping(value = "/lessonEdit", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult updateCourseCreator(@Valid @RequestBody AuthCourseDto authCourseDto) {
        try {
            //更新课程负责人
            authorizeService.updateCourseLeader(authCourseDto.getId(), authCourseDto.getLessonId());
        } catch (ServiceException ex) {
            log.debug("update course leader fail:return false");

            return new JsonResult(false, ex.getMessage().isEmpty() ? "授权失败" : ex.getMessage());
        }

        log.debug("update course leader success:return true");

        return new JsonResult(true, "授权成功");
    }
}
